package com.leetcode.multithreading.licm;

/**
 * @description:
 *
 * 通过volatile实现多线程间共享变量的可见性
 *
 * @author: licm
 * @create: 2021-07-26 10:55
 **/
public class VolatileTest {
    private volatile boolean flag = true;

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    private static class ChangeFlag extends Thread {

        private VolatileTest volatileTest;

        public ChangeFlag(VolatileTest volatileTest) {
            this.volatileTest = volatileTest;
        }

        @Override
        public void run() {
            while (volatileTest.flag) {
                System.out.println("flag是 true");
            }
            System.out.println("flag 已经变成了false");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileTest volatileTest = new VolatileTest();

        ChangeFlag addCount = new ChangeFlag(volatileTest);
        addCount.start();
        Thread.sleep(50);
        volatileTest.setFlag(false);
        ChangeFlag addCount1 = new ChangeFlag(volatileTest);
        addCount1.start();


    }

}
